package cn.ug.analyse.web.controller;

import cn.ug.analyse.bean.ChannelStaffBean;
import cn.ug.analyse.service.ChannelStaffService;
import cn.ug.analyse.web.submit.ChannelStaffSubmit;
import cn.ug.bean.base.SerializeObject;
import cn.ug.core.SerializeObjectError;
import cn.ug.util.ExportExcelUtil;
import cn.ug.web.controller.ExportExcelController;
import org.apache.commons.io.FileUtils;
import org.apache.ibatis.annotations.Param;
import org.dozer.DozerBeanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * @author zhaohg
 * @date 2018/08/06.
 */
@RestController
@RequestMapping("/channel/staff")
public class ChannelStaffController {

    @Autowired
    private ChannelStaffService channelStaffService;
    @Autowired
    private DozerBeanMapper     dozerBeanMapper;

    /**
     * 添加渠道成员
     *
     * @return
     */
    @RequestMapping(value = "/add", method = POST)
    public SerializeObject addChannel(@RequestHeader String accessToken, ChannelStaffSubmit submit) {
        return channelStaffService.insert(submit);
    }

    /**
     * 更新成员启用状态
     *
     * @return
     */
    @RequestMapping(value = "/status", method = POST)
    public SerializeObject updateStatus(@RequestHeader String accessToken, ChannelStaffSubmit submit) {
        if (submit.getId() > 0 && submit.getIsEnable() > -1 && submit.getIsEnable() < 2) {
            return channelStaffService.updateStatus(submit);
        }
        return new SerializeObjectError("00000005");
    }

    @RequestMapping(value = "/reset", method = GET)
    public SerializeObject updateStatus(@RequestHeader String accessToken, Long id) {
        if (id > 0) {
            return channelStaffService.resetPassword(id);
        }
        return new SerializeObjectError("00000005");
    }

    /**
     * 获取渠道成员list
     */
    @RequestMapping(value = "/list", method = GET)
    public SerializeObject findList(@RequestHeader String accessToken, ChannelStaffSubmit submit) {
        if (submit.getChannelId() > 0) {
            return channelStaffService.findList(submit);
        }
        return new SerializeObjectError("00000005");
    }

    @RequestMapping(value = "/export", method = GET)
    public void export( HttpServletResponse response, ChannelStaffSubmit submit) {
        List<ChannelStaffBean> list = channelStaffService.export(submit);
        if (list != null && !list.isEmpty()) {
            String[] columnNames = {"序号", "成员编号", "成员名称", "手机号", "成员状态", "邀请码"};
            String[] columns = {"index", "number", "realName", "mobile", "status", "inviteCode"};
            String fileName = "渠道成员";
            ExportExcelController<ChannelStaffBean> export = new ExportExcelController<>();
            export.exportExcel(fileName, fileName, columnNames, columns, wrapStaffBeanData(list), response, ExportExcelUtil.EXCEL_FILE_2003);
        }
    }

    private List<ChannelStaffBean> wrapStaffBeanData(List<ChannelStaffBean> list) {
        List<ChannelStaffBean> beans = new ArrayList<>();
        int index = 1;
        for (ChannelStaffBean bean : list) {
            ChannelStaffBean channel = dozerBeanMapper.map(bean, ChannelStaffBean.class);
            channel.setIndex(index++);
            channel.setStatus(channel.getIsEnable() > 0 ? "启用" : "禁用");
            beans.add(channel);
        }
        return beans;
    }

    /**
     * excel导入指定渠道成员
     *
     * @param request
     * @param file
     * @return
     */
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    public SerializeObject importStaff(@RequestHeader String accessToken, HttpServletRequest request, @Param("channelId") Long channelId, @RequestParam("file") MultipartFile file) {

        String name = UUID.randomUUID().toString();
        File destFile = new File("/tmp/uploads/" + name, name);
        String path = file.getOriginalFilename();
        String suffix = path.substring(path.lastIndexOf("."), path.length());

        if (".csv".equals(suffix)) {
            try {
                FileUtils.copyInputStreamToFile(file.getInputStream(), destFile);
                return channelStaffService.insertStaffByExcel(destFile, channelId);
            } catch (Exception e) {
                return new SerializeObjectError<>("");
            } finally {
                try {
                    FileUtils.deleteQuietly(destFile);
                } catch (Exception e) {

                }
            }
        } else {
            return new SerializeObjectError<>("00000005");
        }
    }


}
